<template>
  <div class="health-stat-container">
    <el-form :inline="true" class="filter-form">
      <el-form-item label="医疗机构">
        <el-select v-model="form.hospital" placeholder="请选择">
          <el-option label="全部机构" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="病种：">
        <el-select v-model="form.disease" placeholder="请选择">
          <el-option
            v-for="item in diseaseOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="summary-row">
      <el-col :span="6" v-for="(item, index) in totalData" :key="index">
        <div class="summary-card">
          <div class="value" :style="{ color: item.color }">
            {{ item.value }}
          </div>
          <div class="label">{{ item.label }}</div>
        </div>
      </el-col>
    </el-row>

    <el-table :data="tableData" border style="width: 100%" class="data-table">
      <el-table-column prop="index" label="序号" width="80" align="center">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        prop="organization"
        label="机构/家医团队"
        width="200"
        fixed
      />

      <el-table-column prop="total" label="患者总数" align="center" />

      <el-table-column prop="highRisk" label="极高危人群" align="center" />

      <el-table-column prop="danger" label="高危人群" align="center" />

      <el-table-column prop="mediumRisk" label="中危人群" align="center" />

      <el-table-column prop="lowRisk" label="低危人群" align="center" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const form = reactive({
  hospital: '',
  disease: '高血压'
});

const diseaseOptions = ref(['高血压', '糖尿病', '肥胖症']);
const totalData = ref(createSummaryTemplate());
const tableData = ref([]);

// 初始化汇总数据结构
function createSummaryTemplate() {
  return [
    { label: '患者总人数', value: 0, color: '#333' },
    { label: '极高群体', value: 0, color: '#ff0000' },
    { label: '高危群体', value: 0, color: '#ffa500' },
    { label: '中危群体', value: 0, color: '#ffff00' }
  ];
}

// 数据处理核心方法
const processData = (rawData, disease) => {
  // 前端筛选逻辑
  let filteredData = [...rawData];
  if (disease === '肥胖症') {
    filteredData = filteredData.filter((p) => p.bmi >= 28);
  }

  // 机构数据聚合
  const orgMap = filteredData.reduce((map, patient) => {
    const org = patient.orgName || '未知机构';
    if (!map.has(org)) {
      map.set(org, {
        organization: org,
        total: 0,
        highRisk: 0,
        danger: 0,
        mediumRisk: 0,
        lowRisk: 0
      });
    }
    const orgData = map.get(org);
    orgData.total++;
    if (patient.hypertension === 1) orgData.highRisk++;
    if (patient.diabetes === 1) orgData.danger++;
    if (patient.bmi >= 28) orgData.mediumRisk++;
    return map;
  }, new Map());

  // 计算低危人群
  Array.from(orgMap.values()).forEach((org) => {
    org.lowRisk = Math.max(
      0,
      org.total - (org.highRisk + org.danger + org.mediumRisk)
    );
  });

  return {
    tableData: Array.from(orgMap.values()),
    totals: {
      total: filteredData.length,
      highRisk: filteredData.filter((p) => p.hypertension === 1).length,
      danger: filteredData.filter((p) => p.diabetes === 1).length,
      mediumRisk: filteredData.filter((p) => p.bmi >= 28).length
    }
  };
};

// 数据加载
const loadData = async () => {
  try {
    const params = {
      PageIndex: 1,
      PageSize: 1000, // 假设需要获取全部数据
      OrgName: form.hospital || undefined,
      Hypertension: form.disease === '高血压' ? 1 : undefined,
      Diabetes: form.disease === '糖尿病' ? 1 : undefined
    };

    const res = await axios.get(
      apiUrl + '/T7/Medical/ManagementhierarchyQuery',
      { params }
    );

    if (res.data.code === 210) {
      const { tableData: processedData, totals } = processData(
        res.data.list,
        form.disease
      );

      tableData.value = processedData;
      totalData.value[0].value = totals.total;
      totalData.value[1].value = totals.highRisk;
      totalData.value[2].value = totals.danger;
      totalData.value[3].value = totals.mediumRisk;
    }
  } catch (error) {
    console.error('数据加载失败:', error);
    ElMessage.error('数据加载失败，请稍后重试');
  }
};

// 查询/重置处理
const handleQuery = () => loadData();
const handleReset = () => {
  form.hospital = '';
  form.disease = '高血压';
  loadData();
};

// 初始化加载
onMounted(loadData);
</script>

<style scoped>
.health-stat-container {
  padding: 20px;
  background: #fff;
}

.filter-form {
  margin-bottom: 20px;
}

.summary-row {
  margin-bottom: 20px;
}

.summary-card {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  transition: transform 0.3s;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.summary-card .value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.summary-card .label {
  color: #666;
  font-size: 14px;
}

.data-table {
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-select {
  width: 150px;
}

@media (max-width: 768px) {
  .el-col-6 {
    width: 100%;
    margin-bottom: 15px;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
}
</style>
